package com.caogt.zuul.login;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;

//@Component
public class LoginFilter  extends ZuulFilter {

    private static final String[] exclude_url = new String[]{"js","css","png","jpg"};
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 3;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext= RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest=requestContext.getRequest();

        String uri = httpServletRequest.getRequestURI();
        if(uri.indexOf(".") > -1){
            String end = uri.substring(uri.lastIndexOf("."));
            for(String e : exclude_url){
                if(e.equalsIgnoreCase(end)){
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public Object run() {
        RequestContext requestContext= RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest=requestContext.getRequest();
        String token = httpServletRequest.getParameter("token");
        if(!checkToken(token)){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }else{
            requestContext.addZuulRequestHeader("zuulForward","true");
            requestContext.setSendZuulResponse(true);
            requestContext.setResponseStatusCode(HttpStatus.SC_OK);
        }
        return null;
    }

    private boolean checkToken(String token){
        boolean rest = true;
        if(token == null){
            rest = false;
        }
        return rest;
    }
}
